package cn.com.yusys.yusp.admin.web.rest;

import cn.com.yusys.yusp.admin.Utils.IDUtils;
import cn.com.yusys.yusp.admin.service.CustCenterService;
import cn.com.yusys.yusp.admin.service.VillageInformationService;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import cn.com.yusys.yusp.mobile.web.rest.SunEcmFileInfoQryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/villageInformation")
public class VillageInformationResource {


    @Value("${filmUrl.testUrl}")
    private String filmUrl;

    @Autowired
    private VillageInformationService villageInformationService;

    //显示所有的存信息,例如根据登录的用户id去查询此id属于哪一块,再根据用户信息表查询此人的级别，
    // 如果是最底层，就显示归属于该用户的机构的村，如果是客户经理就显示该经理管辖下，所有业务员的客户
    @GetMapping("/getAllVillageInformation")
    public ResultDto<List<Map<String, Object>>> getAllVillageInformation(QueryModel queryModel){
        String roleId= (String) queryModel.getCondition().get("roleId");
        List<Map<String, Object>> list = new ArrayList<>();
        String orgId = (String)queryModel.getCondition().get("orgId");
        //如果orgId属于以上职业，则属于分行行长，显示分行下所有客户信息
        if (orgId.equals("070667XN0") || orgId.equals("070667XN1") ||orgId.equals("070667860") ||orgId.equals("070667XN3")){
            list = villageInformationService.getBranchManagerVillageInformation(queryModel);
            return new ResultDto<>(list);
        }
        //查询该客户经理所属的网格下的用户
        if (roleId.equals("R0001") || roleId.equals("R0002") || roleId.equals("R0009")){
            list = villageInformationService.getCustomerManagerVillageInformation(queryModel);
        }
        //查询所有用户
        if (roleId.equals("R0008") || roleId.equals("R0007") || roleId.equals("R001")){
            list = villageInformationService.getAllVillageInformation(queryModel);
        }
        //查询支行下所属的所有客户经理的用户 Sub-branch Manager
        if (roleId.equals("R0006") || roleId.equals("R0005") || roleId.equals("R0003") || roleId.equals("R0004")){
            list = villageInformationService.getSubBranchManagerVillageInformation(queryModel);
        }
        return new ResultDto<>(list);
    }

    @GetMapping("/getOtherIndustry")
    public ResultDto<List<Map<String, Object>>> getOtherIndustry(QueryModel queryModel){
        List<Map<String, Object>> list = villageInformationService.getOtherIndustry(queryModel);
        //如果orgId属于以上职业，则属于分行行长，显示分行下所有客户信息
        return new ResultDto<>(list);
    }

    @GetMapping("/getOtherIndustryName")
    public ResultDto<List<Map<String, Object>>> getOtherIndustryName(QueryModel queryModel){
        List<Map<String, Object>> list = villageInformationService.getOtherIndustryName(queryModel);
        //如果orgId属于以上职业，则属于分行行长，显示分行下所有客户信息
        return new ResultDto<>(list);
    }

    //取得主要行业客户列表
    @GetMapping("/getVillageCustList")
    public ResultDto<List<Map<String, Object>>> getVillageCustList(QueryModel queryModel){
        List<Map<String, Object>> list = villageInformationService.getVillageCustList(queryModel);
        //如果orgId属于以上职业，则属于分行行长，显示分行下所有客户信息
        return new ResultDto<>(list);
    }

    //取得次要行业客户列表
    @GetMapping("/getOtherIndustryCustList")
    public ResultDto<List<Map<String, Object>>> getOtherIndustryCustList(QueryModel queryModel){
        List<Map<String, Object>> list = villageInformationService.getOtherIndustryCustList(queryModel);
        //如果orgId属于以上职业，则属于分行行长，显示分行下所有客户信息
        return new ResultDto<>(list);
    }


    /**
     * 新增村
     */
    @GetMapping("/addVillage")
    public ResultDto<Integer> addVillage(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.addVillage(queryModel));
    }

    /**
     * 新增村
     */
    @GetMapping("/addOtherIndustry")
    public ResultDto<Integer> addOtherIndustry(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.addOtherIndustry(queryModel));
    }

    @GetMapping("/deleteOtherIndustry")
    public ResultDto<Integer> deleteOtherIndustry(QueryModel queryModel) {
        List<Integer> list = (List<Integer>)queryModel.getCondition().get("industryId");
        return  new ResultDto<>(villageInformationService.deleteOtherIndustry(list));
    }

    /**
     * 查询选定的村信息
     *
     */
    @GetMapping("/getVillageInformation")
    public ResultDto<Map<String, Object>> getVillageInformation(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.getVillageInformation(queryModel));
    }

    @GetMapping("/getVillageIndustryInformation")
    public ResultDto<Map<String, Object>> getVillageIndustryInformation(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.getVillageIndustryInformation(queryModel));
    }

    @GetMapping("/getGridPersonnel")
    public ResultDto<Map<String, Object>> getGridPersonnel(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.getGridPersonnel(queryModel));
    }

    /**
     * 查询选定的村详细
     */
    @GetMapping("/getVillageDetail")
    public ResultDto<Map<String, Object>> getVillageDetail(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.getVillageDetail(queryModel));
    }

    @GetMapping("/getOtherIndustryDetail")
    public ResultDto<Map<String, Object>> getOtherIndustryDetail(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.getOtherIndustryDetail(queryModel));
    }

    //查看村详细信息图片，查询返回客户编号，村庄信息（一个）传入值为村庄id和客户id 列表查询
    @GetMapping("/getVillageCustDetailImage")
    public ResultDto<Map<String, Object>> getVillageCustDetailImage(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.getVillageCustDetailImage(queryModel));
    }

    @GetMapping("/getOtherIndustryCustDetailImage")
    public ResultDto<Map<String, Object>> getOtherIndustryCustDetailImage(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.getOtherIndustryCustDetailImage(queryModel));
    }
    /**
     * 修改村信息
     *
     */
    @GetMapping("/updateVillageInformation")
    public ResultDto<Integer> updateVillageInformation(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.updateVillageInformation(queryModel));
    }

    @GetMapping("/updateOtherIndustry")
    public ResultDto<Integer> updateOtherIndustry(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.updateOtherIndustry(queryModel));
    }

    @GetMapping("/addVillageDetail")
    public ResultDto<Integer> updateVillageDetail(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.addVillageDetail(queryModel));
    }

    @GetMapping("/addOtherIndustryDetail")
    public ResultDto<Integer> updateOtherIndustryDetail(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.addOtherIndustryDetail(queryModel));
    }

    @GetMapping("/updateGridPersonnel")
    public ResultDto<Integer> updateGridPersonnel(QueryModel queryModel) {
        return  new ResultDto<>(villageInformationService.updateGridPersonnel(queryModel));
    }


    /**
     * 将web上的上传文件存储指定位置中
     * @param file
     * @return
     */
    @PostMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(MultipartFile file) {
        return villageInformationService.fileUpload(file);
    }

    /**
     * 村信息
     */


    /**
     * 新增次要行业信息（用另外一张表进行关联)
     */

    /**
     * 将内网URL转换为base64图片数据
     *
     * @param url
     * @return byte[]
     */
    public static String getFileBytesFromHttpUrl(String url) {
        HttpURLConnection conn = null;
        ByteArrayOutputStream out = null;
        InputStream in = null;
        byte[] result = null;
        try {
            out = new ByteArrayOutputStream();
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setDoInput(true);
            conn.connect();
            in = conn.getInputStream();

            byte[] buff = new byte[128];
            int flag = -1;
            while ((flag = in.read(buff)) != -1) {
                out.write(buff, 0, flag);
            }
            result = out.toByteArray();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            try {
                in.close();
                out.close();
                conn.disconnect();
            } catch (IOException ignore) {
            }
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(result);
    }
    /**
     * 获取图片
     */
    @GetMapping("/getPhoto")
    public ResultDto<Map> getPhoto(QueryModel queryModel) {
        //service.getFiles(request, this.json);
        Map map=new HashMap();
        SunEcmFileInfoQryService sunEcmFileInfoQryService = new SunEcmFileInfoQryService();
        // 初始化影像平台服务 ip,port 组名
        sunEcmFileInfoQryService.setGroupname("SunECMDM");
        //测试
        sunEcmFileInfoQryService.setIp(filmUrl);
        //生产
//        sunEcmFileInfoQryService.setIp("192.168.220.120");
        sunEcmFileInfoQryService.setSocketport(8022);
        try {
            List<Map<String,String>> arrlist=new ArrayList<Map<String,String>>();
            HashMap yxparams = new HashMap();
            //影像平台配置信息可迁移
//            yxparams.put("DocId", request.getParameter("docId")); // 影像流水号
            yxparams.put("DocId", (String) queryModel.getCondition().get("actFile")); // 影像流水号
            yxparams.put("ModelCode", "YDYHGTGSHZF");
            yxparams.put("FilePartName", "YDYHGTGSHZFP");
            yxparams.put("SunEcmUserName", "WGHYXXT"); // 账号
            yxparams.put("SunEcmPassword", "qwer1234"); // 密码
            yxparams.put("FileType", null);
            Map resultMap = sunEcmFileInfoQryService.SunEcmFileInfoQry(yxparams);
            //如果结果为空，那么调用影响平台查找
            // 打印返回信息
            List<Map> fileList = (List) resultMap.get("List");
            System.out.println(fileList);
            if (fileList.size() > 0) {
                System.out.println(fileList);
                for (Map<String,Object> info : fileList) {
                    Map<String,String> fileMap=new HashMap<String,String>();
                    fileMap.put("base64",((String) info.get("FileUrl")));
                    arrlist.add(fileMap);
                }
            }
            map.put("arrlist",arrlist);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new ResultDto(map);
    }

}
